package com.artisan.web.action;

import com.alibaba.fastjson.JSON;
import com.artisan.common.pojo.ApiRes;
import com.artisan.common.utils.SendPhone;
import com.artisan.common.utils.Utils;
import com.artisan.common.utils.wxpay.HttpClientUtil;
import com.artisan.medium.wx.pojo.AccessToken;
import com.artisan.medium.wx.pojo.WxUserInfo;
import com.artisan.medium.wx.service.WxUserService;
import com.artisan.medium.wx.utils.AccessTokenUtils;
import com.artisan.model.Customer;
import com.artisan.web.utils.SendMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.jms.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yang on 2017/6/18.
 */
@Controller
@RequestMapping("/wx/user/")
public class WxUserContoller {

    @Autowired
    private WxUserService  wxUserService;

    /**
     * 进入登录页
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("index")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> resultData = new HashMap<String, Object>();

        AccessToken at=null;
        if(request.getSession().getAttribute("token")!=null){
            at=(AccessToken) request.getSession().getAttribute("token");
        }else{
            String code = request.getParameter("code");
            at = AccessTokenUtils.getAccessTokenUtil(code);
            request.getSession().setAttribute("token",at);
        }
       String openid = at.getOpenid();

        Customer customer=wxUserService.getCustomerByOpenId(openid);
        if(customer==null){
            resultData.put("openid",openid);
            return new ModelAndView("login",resultData);
        }else{
            request.getSession().setAttribute("USER",customer);
            return new ModelAndView("my",resultData);
        }

    }

    /**
     * 发送短信验证码
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "sendSC",method = RequestMethod.GET)
    public String sendSC(HttpServletRequest request, HttpServletResponse response) {
        String phone=request.getParameter("phone");
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> resultData = new HashMap<String, Object>();
        if(wxUserService.checkSendOK(phone)>0){
            resultData.put("result", ApiRes.ERROR_CODE);
            resultData.put("msg","验证码请求过于频繁，休息一下!");
            return JSON.toJSONString(resultData);
        }
        String wxValue= Utils.getRandomNumber(4);
        String res=SendMsg.getVerifyCode(phone,wxValue);
        boolean result = "0".equals(res.substring(0,1))?true:false;
        if(result){
            wxUserService.insertSmsInfo(phone, wxValue);
            resultData.put("result",ApiRes.SUCCESS_CODE);
            resultData.put("msg","验证码发送成功!");
            resultData.put("value",wxValue);
        }else {
            resultData.put("result",ApiRes.ERROR_CODE);
            resultData.put("msg","验证码发送失败!");
        }
        return JSON.toJSONString(resultData);
    }

    @ResponseBody
    @RequestMapping(value = "loginOut",method = RequestMethod.GET)
    public String loginOut(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultData = new HashMap<String, Object>();
        Customer customer=null;
        if( request.getSession().getAttribute("USER")!=null) {
            customer = (Customer) request.getSession().getAttribute("USER");
            wxUserService.loginOut(customer);
            request.getSession().removeAttribute("USER");
            request.getSession().removeAttribute("TOKEN");
        }
        return JSON.toJSONString(resultData);
    }

    /**
     * 用户登录
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "login",method =RequestMethod.GET )
    public String login(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultData = new HashMap<String, Object>();
       String openid=request.getParameter("openid");
        String phone = request.getParameter("phone");
        String value=request.getParameter("value");
        System.out.println("login方法：openid="+openid);
        int state= wxUserService.checkLogin(phone,value);
        if(state>0){
                //验证成功
              Customer customer=wxUserService.getCustomerByOpenId(openid);
            System.out.println("customer="+customer);
              if(customer==null){
                  HttpClientUtil util = HttpClientUtil.getInstance();
                  Map<String, Object> wxData = new HashMap<String, Object>();
                  AccessToken accessToken = AccessTokenUtils.getToken();
                  wxData.put("access_token",accessToken.getAccess_token());
                  System.out.println("access_token="+accessToken);

                  wxData.put("openid",openid);
                  String returnStr= null;
                  try {
                      returnStr = util.getResponseBodyAsString("https://api.weixin.qq.com/cgi-bin/user/info", wxData);
                      WxUserInfo wxUserInfo = JSON.parseObject(returnStr, WxUserInfo.class);
                      System.out.println("wxUserInfo="+wxUserInfo.toString());
                      /*request.getSession().setAttribute("TOKEN",accessToken);*/
                      customer=wxUserService.getCustomerByPhone(phone);
                      //判断手机号是否存在
                      if(customer!=null){
                          customer.setOpenId(wxUserInfo.getOpenId());
                          wxUserService.login(customer);
                      }else{
                          customer=new Customer();
                          customer.setPhone(phone);
                          customer.setwName(wxUserInfo.getNickname());
                          customer.setOpenId(wxUserInfo.getOpenId());
                          customer.setLogo(wxUserInfo.getHeadImgUrl());
                          customer.setUpdateTime(new Date());
                          customer.setCrtTime(new Date());
                          customer.setLastTime(new Date());
                          int uid= wxUserService.bingDingPhone(customer);
                          customer.setId(uid);
                      }

                      request.getSession().setAttribute("USER",customer);
                  } catch (Exception e) {
                      System.out.println( e.toString());
                      e.printStackTrace();

                  }

              }

            resultData.put("result",ApiRes.SUCCESS_CODE);
            resultData.put("msg","登录成功!");
        }else{
            resultData.put("result",ApiRes.ERROR_CODE);
            resultData.put("msg","验证码失效!");
        }
        System.out.println("接口返回值:"+JSON.toJSONString(resultData));
        return JSON.toJSONString(resultData);
    }

    /**
     * 进入我的个人中心
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("center")
    public ModelAndView my(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = request.getParameter("code");
        System.out.println("center方法:code="+code);
        Map<String, Object> resultData = new HashMap<String, Object>();
        Customer customer=null;
        if( request.getSession().getAttribute("USER")!=null){
            customer=(Customer) request.getSession().getAttribute("USER");
            request.getSession().setAttribute("USER",customer);
            resultData.put("customer",customer);
            return new ModelAndView("my",resultData);
        }else{
            if(!StringUtils.isEmpty(code)){
                resultData.put("code",code);
            }
            //查看opendId是否绑定
            AccessToken at=null;
            if(request.getSession().getAttribute("TOKEN")!=null){
                at=(AccessToken) request.getSession().getAttribute("TOKEN");
            }else{
                code = request.getParameter("code");
                at = AccessTokenUtils.getAccessTokenUtil(code);
                request.getSession().setAttribute("TOKEN",at);
            }
            String openid = at.getOpenid();;
            System.out.println("openId:"+openid);
            customer=wxUserService.getCustomerByOpenId(openid);
            if(customer==null){
                resultData.put("openid",openid);
                return new ModelAndView("my_reg",resultData);
            }else{
                request.getSession().setAttribute("USER",customer);
                resultData.put("customer",customer);
                return new ModelAndView("my",resultData);
            }
        }
    }

    /**
     * 编辑用户
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("updateUser")
    public ModelAndView updateUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> resultData = new HashMap<String, Object>();
        Customer customer=(Customer)request.getSession().getAttribute("USER");
        if(customer==null){
            return new ModelAndView("my_reg",resultData);
        }else{
            resultData.put("customer",customer);
            return new ModelAndView("my_detail",resultData);
        }
    }


    /**
     * 获取地址
     * @param request
     * @param response
     * @return
     */
    public String getAddress(HttpServletRequest request, HttpServletResponse response){
        //获取用户默认地址
        return "";
    }

    /**
     * 添加地址
     * @param request
     * @param response
     * @return
     */
    public String addAddress(HttpServletRequest request, HttpServletResponse response){
        String  name=request.getParameter("name");
        String  phone=request.getParameter("phone");
        /*String  name=request.getParameter("name");*/
        String  addressDetail=request.getParameter("addressDetail");
        //获取用户默认地址
        return "";
    }

    /**
     * 关于我们
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("about")
    public ModelAndView aboutUs(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return new ModelAndView("about");
    }



}
